# -*- coding: utf-8 -*-
from flask import (
    session,
    request
)
from flask_socketio import (
    SocketIO,
    emit
)

from threading import Lock
import time


socketio = SocketIO(path='ws', logger=False, engineio_logger=False)
thread = None
thread_lock = Lock()

@socketio.on('my event')
def test_message(message):
    emit(
        'my response',
        {'data': 'got it!'},
        namespace='/ns'
    )

def get_log():
    return {
        'msg': 'test info message',
        'level': 'info',
        'timestamp': int(time.time())
    }

def background_thread():
    """Example of how to send server generated events to clients."""
    count = 0
    while True:
        socketio.sleep(2.5)
        count += 1
        socketio.emit(
            'server_response',
            {
                'data': 'Server generated event',
                'count': count
            },
            namespace='/ns'
        )
        socketio.send({'send_event': count}, namespace='/ns')
        socketio.emit(
            'send_log',
            get_log(),
            namespace='/ns'
        )

def ack():
    print('message was received!')

@socketio.on('connect', namespace='/ns')
def test_connect():
    '''
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=background_thread)
    '''
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit(
        'server_response',
        {
            'data': 'Connected',
            'count': session['receive_count']
        },
        namespace='/ns'
    )


@socketio.on('disconnect', namespace='/ns')
def test_disconnect():
    print('Client disconnected', request.sid)

@socketio.on('message', namespace='/ns')
def handle_message(message):
    print('received message: ' + message)
    emit('my_response', message, callback=ack)

@socketio.on('json', namespace='/ns')
def handle_json(json):
    print('received json: ', end='')
    print(json)
    emit('my_response', ('foo', 'bar', json), namespace='/ns')

@socketio.on('write_task_log', namespace='/ns')
def handle_task_log(message):
    socketio.emit(
        'send_log',
        task_log(message),
        namespace='/ns'
    )

def task_log(message):
    return {
        'msg': message,
        'level': 'info',
        'timestamp': int(time.time())
    }

@socketio.on('send_log', namespace='/task')
def handle_task_callback(message):
    socketio.emit(
        'send_log',
        task_log(message),
        namespace='/ns'
    )